package com.liu.maven;

import java.io.File;
import java.io.FileWriter;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.junit.Test;

public class Dom4j {
	
	@Test
	public void add() throws Exception {
		SAXReader reader=new SAXReader();
		Document document = reader.read(new File("c:\\book.xml"));
//		BookUtil.print(document);
		
		//获得根节点
		Element rootElement = document.getRootElement();
		List<Element> elements = rootElement.elements();
		
		//获得某个节点的子节点
		Element element = rootElement.element("book");
		
		
		
		//获得某节点下的属性
		Attribute att = rootElement.attribute("id");
		//获得属性下的文字
		String text = att.getText();
		//删除某属性
		rootElement.remove(att);
		
		//遍历某节点所有属性
		Iterator it = rootElement.attributeIterator();
		while(it.hasNext()){
			Attribute attribute = (Attribute)it.next();
			String atext=attribute.getText();
			System.out.println(atext);
		}
		
		//将文档写入xml文件
		XMLWriter writer=new XMLWriter(new FileWriter("c:\\book.xml"));
		writer.write(document);
		writer.close();
		
		//创建文件输出自动缩进格式
		OutputFormat format=OutputFormat.createPrettyPrint();
		format.setEncoding("utf-8");
		new XMLWriter(new FileWriter("c:\\books.xml"),format);
		writer.write(document);
		writer.close();
		
		//讲字符串转化为xml
		String st="<csdn> <java>Java班</java></csdn>";
		Document ddcument = DocumentHelper.parseText(st);
		
		//将文档或节点的xml转化为字符串
		String docXmltext = document.asXML();
		String rootAsXml = rootElement.asXML();
		
		
		
		
		
	
		
		Iterator iterator = elements.iterator();
		
		while(iterator.hasNext()){
			Element e = (Element)iterator.next();
			Attribute id = e.attribute("id");
//			String name = id.getName();
//			System.out.println(e.getName()+name+e.attributeValue("id")+e.getStringValue());
			
			
		}
		
		
		
		
		
		
	}

}